# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '17/10/2024'
    comment: 流程节点
"""
from sqlalchemy import func
from fastapi import APIRouter, Request, Query, Body

from config import Config
from project.core.function import json_response, if_none
from project.lib.validators import generate_validator, DateStr
from project.lib.decorator import api_common, exec_duration
from project.model.database.record import FlowRecord
from project.model.database.flow import Flow
from project.service.record import RecordService


record_router = APIRouter(prefix='/m', tags=['manager.record'])


@record_router.get('/flow/record/list_page', summary='服务记录列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def get_flow_record_list(request: Request,
                               status: str = Query('', title='服务记录状态', description='init(待完成)/success(已完成)/cancel(已取消)'),
                               flow_id: int = Query(0, title='服务流程id'),
                               flow_code: str = Query('', title='服务流程code'),
                               room_no: str = Query('', title='房间号'),
                               start_date: generate_validator(DateStr, blank_enable=True) = Query('', title='开始日期', description='格式: yyyy-mm-dd'),
                               end_date: generate_validator(DateStr, blank_enable=True) = Query('', title='结束日期', description='格式: yyyy-mm-dd'),
                               page: int = Query(1, title='第几页', description='默认1'),
                               page_size: int = Query(20, title='条数', description='每页显示的条数'),
                               session=None,
                               operator=None):
    """
    **desc**: 服务记录列表(分页)

    **url**: http(s)://{0}.udicaria.com/m/flow/record/list_page

    **method**: GET

    **params**:

        <query>:
            status: 服务记录状态 init(待完成)/success(已完成)/cancel(已取消)
            flow_id: 服务流程id
            flow_code: 服务流程code
            room_no: 房间号
            start_date: 开始日期
            end_date: 结束日期
            page: 页号
            page_size: 每页条数

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: {
                num: 条数
                items: [
                    {
                        code: 服务编号
                        flow_name: 服务类型
                        room_no: 服务地址
                        create_time: 发起时间
                        status: 状态
                        flow_process_name: 当前节点
                        update_time: 操作时间
                    }
                ]
            }
            exec_time: 接口后端处理时长
        }
    """
    wheres = list()
    if status:
        wheres.append(FlowRecord.status == status)
    if flow_id:
        wheres.append(FlowRecord.flow_id == flow_id)
    if flow_code:
        wheres.append(FlowRecord.flow_code == flow_code)
    if room_no:
        wheres.append(FlowRecord.room_no.like(f'%{room_no}%'))
    if start_date:
        wheres.append(FlowRecord.business_date >= start_date)
    if end_date:
        wheres.append(FlowRecord.business_date <= end_date)
    wheres.append(FlowRecord.organization_code == operator.organization_code)
    wheres.append(~FlowRecord.is_deleted)

    # num
    record = await FlowRecord.fetch_one(session,
                                        selects=(func.count(FlowRecord.id)),
                                        wheres=wheres)
    num = if_none(record[0], 0)

    data = await FlowRecord.fetch_all(session,
                                      selects=(FlowRecord, Flow),
                                      joins=((Flow, Flow.id == FlowRecord.flow_id),),
                                      wheres=wheres,
                                      offset=(page - 1) * page_size,
                                      limit=page_size,
                                      orders=FlowRecord.id.desc())

    items = []
    for flow_record, flow in data:
        d = flow_record.dict()
        d['flow_name'] = flow.name
        items.append(d)

    ret_data = {
        'num': num,
        'items': items
    }

    return json_response(data=ret_data)


@record_router.get('/flow/record/count', summary='服务记录条数')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def get_flow_record_count(request: Request,
                                status: str = Query('init', title='服务记录状态', description='init(待完成)/success(已完成)/cancel(已取消)'),
                                session=None, operator=None):
    """
    **desc**: 服务记录数量

    **url**: http(s)://{0}.udicaria.com/m/flow/record/count

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: {
                num: 数据条数
                items: [
                    {
                        id: 服务记录id（用于查询详情）
                        code: 服务编号
                        classify_name: 服务类型
                        room_no: 房间号
                        create_time: 发起时间
                        update_time: 操作时间
                        classify_process_name: 当前节点
                    }
                ]
            }
            exec_time: 接口后端处理时长
        }
    """
    # num
    record = await FlowRecord.fetch_one(session,
                                        selects=(func.count(FlowRecord.id)),
                                        wheres=(FlowRecord.status == status, ~FlowRecord.is_deleted, FlowRecord.organization_code == operator.organization_code))
    num = if_none(record[0], 0)

    return json_response(data={'num': num})


@record_router.get('/flow/record/detail', summary='服务记录详情')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), verify_login=True)
@exec_duration(add_return=True)
async def get_flow_record_detail(request: Request,
                                 id: int = Query(..., title='服务记录id'),
                                 session=None):
    """
    **desc**: 服务记录详情

    **url**: http(s)://{0}.udicaria.com/m/flow/record/detail

    **method**: GET

    **params**:

        <query>:
            id: 服务记录id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: {
                id: 服务记录id
                code: 服务记录编号
                flow_code: 服务流程编号
                flow_name: 服务流程名称
                flow_process_id: 流程状态id
                flow_process_name: 流程状态名称
                room_no: 房间号
                dev_id: 设备编号
                content: [
                    {
                        title: 项目名称
                        value: 项目值
                        items: [
                            {
                                title: 商品名
                                count: 商品数量
                                price: 商品单价
                                spec: [] 规格信息 [{"title": xxx, "items": [xxx, xxx, xxx]}, {"title": xxx, "items": [xxx, xxx, xxx]}]
                            }
                            ...
                        ]
                    }
                    ...
                ] 服务内容
                flow_record_logs: [
                    {
                        record_status: 节点
                        flow_process_id: 节点状态id
                        flow_process_name: 节点状态名称
                        record_status: 服务记录状态 init(待完成)/success(已完成)/cancel(已取消)
                        flow_role_name: 服务人员
                        flow_role_phone: 联系电话
                        create_time: 操作时间
                    }
                ] 流程状态

                invoice: {
                    room_number: 房间号
                    invoice_type: 发票类型(electronic(电子发票)/paper(纸质发票))
                    title_type: 抬头类型(enterprise(企业单位)/individual(个人/非企业单位)
                    invoice_title: 发票抬头
                    tax_number: 税号
                    email: 邮箱
                    bank_name: 开户银行
                    bank_account: 银行账号
                    company_address: 公司地址
                    company_phone: 公司电话
                } 发票信息
            }
            exec_time: 接口后端处理时长
        }
    """
    data = await RecordService.get_flow_record_detail(session, flow_record_id=id)

    return json_response(data=data)


@record_router.post('/flow/record/cancel', summary='取消服务记录')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def do_flow_cancel(request: Request,
                         id: int = Body(..., title='服务记录id', embed=True),
                         session=None, device=None):
    """
    **desc**: 服务记录取消

    **url**: http(s)://{0}.udicaria.com.udicaria.com/m/flow/record/cancel

    **method**: POST

        <body>:
            flow_code: 服务流程编号

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    await RecordService.do_flow_record_cancel(session, flow_record_id=id)

    return json_response()

